#
#  Copyright 2008 Garth Williams
#
#  This file is part of CommandPost.
#
#  CommandPost is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  CommandPost is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with CommandPost.  If not, see <http://www.gnu.org/licenses/>.
#

class AddInitialRolesAndUsers < ActiveRecord::Migration
  def self.up
    User.transaction do
      log = Log.new(:summary => 'CommandPost installed',
        :description => 'Congratulations, CommandPost has been successfully installed!',
        :created_by => nil)
      log.save!
      administrator = User.new(:login => 'admin', :name => 'Administrator',
        :email => 'admin@some.org', :password => 'admin', :password_confirmation => 'admin')
      administrator.save!
      log.created_by = administrator
      log.save!
      administrators = Role.new(:name => 'Administrators', :system => true, :created_by => administrator)
      administrators.save!
      RolesUser.new(:user => administrator, :role => administrators, :created_by => administrator).save!
      Role.new(:name => 'ReportTypeAdministrators', :system => true, :created_by => administrator).save!
      Role.new(:name => 'Guests', :system => true, :created_by => administrator).save!
      Role.new(:name => 'PageAuthors', :system => true, :created_by => administrator).save!
      Role.new(:name => 'MilestoneManagers', :system => true, :created_by => administrator).save!
    end
  end

  def self.down
    User.transaction do
      Log.destroy_all
      administrator = User.find_by_name('Administrator')
      administrators = Role.find_by_name('Administrators')
      RolesUser.destroy_all(['user_id = ? OR role_id = ?', administrator.id, administrators.id])
      administrator.destroy
      administrators.destroy
      Role.find_by_name('ReportTypeAdministrators').destroy
      Role.find_by_name('Guests').destroy
      Role.find_by_name('PageAuthors').destroy
      Role.find_by_name('MilestoneManagers').destroy
    end
  end
end